package com.running.base.run.util;

import com.running.base.run.exception.BizException;
import com.running.base.run.exception.enums.CommonEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

/**
 * 发送邮件工具
 */
@Component
public class SendMail {

    private static final Logger logger = LoggerFactory.getLogger(SendMail.class);

    /**
     * 发件人邮箱账密可重新配置
     */
    @Value("${sender.email}")
    private String myEmailAccount;

    @Value("${sender.email.paswd}")
    private String myEmailPassword;

    @Value("${sender.email.smtp}")
    private String myEmailSMTPHost;

    @Value("${sender.email.port}")
    private String myEmailSMTPPort;

    @Value("${email.application.name}")
    private String mailAppName;

    /**
     * @param receiveEmail 接收邮箱
     * @param receiveUser 接收用户
     * @param content 邮件内容
     * @throws Exception
     * jdk-8u151及之前版本
     */
    public void sendEmail(String subject, String receiveEmail, String content) {
        try {
            logger.info("邮件发送，接收邮箱={}", receiveEmail);
            // 1. 创建参数配置, 用于连接邮件服务器的参数配置
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.host", myEmailSMTPHost);
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.port", myEmailSMTPPort);
            props.setProperty("mail.smtp.socketFactory.port", myEmailSMTPPort);
            props.setProperty("mail.smtp.starttls.enable", "true");

            if (myEmailAccount.contains("outlook")) {//outlook邮箱
                props.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
            } else {
                final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
                props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            }

            Session session = Session.getInstance(props);
            session.setDebug(true);

            MimeMessage message = createMimeMessage(session, subject, myEmailAccount, receiveEmail, content);

            Transport transport = session.getTransport();

            transport.connect(myEmailAccount, myEmailPassword);

            transport.sendMessage(message, message.getAllRecipients());

            transport.close();

            logger.info("邮件发送成功,邮件内容：{}", content);
        } catch (Exception e) {
            logger.error("发送邮件失败：", e);
            throw new BizException(CommonEnum.EMAIL_SEND_ERROR);
        }
    }


    /**
     * 创建一封只包含文本的简单邮件
     *
     * @param session     和服务器交互的会话
     * @param sendMail    发件人邮箱
     * @param receiveMail 收件人邮箱
     * @return
     * @throws Exception
     */
    private MimeMessage createMimeMessage(Session session, String subject, String sendMail, String receiveMail, String content) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        message.setFrom(new InternetAddress(sendMail, mailAppName, "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail));

        // 4. Subject: 邮件主题
        message.setSubject(subject, "UTF-8");

        // 5. Content: 邮件正文（可以使用html标签）
        message.setContent(content, "text/html;charset=UTF-8");
        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }
}
